package com.homework.api_user.controller;

import com.homework.api_user.services.UserService;
import com.homework.dao.domain.Token;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.net.http.HttpResponse;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 注册
     */
    @RequestMapping("/register/{email}/{password}/{code}")
    public ResultMsg register(@PathVariable("email") String email, @PathVariable("password") String passwd, @PathVariable("code") String code) {
        if(email.length() == 0 || passwd.length() == 0 || code.length() == 0) {
            return ResultUtil.error(1, "请输入完整的邮箱， 密码和验证码");
        }

        boolean bool = userService.isRegister(email);
        if(bool == true) {
            return ResultUtil.error(2, "该邮箱已注册！");
        }

        return userService.register(email, passwd, code);
    }

    @RequestMapping("/isRegistered/{email}")
    public ResultMsg isRegister(@PathVariable("email") String email) {
        if(email == null || email.length() == 0) {
            return ResultUtil.error(1, "请输入email");
        }

        boolean bool = userService.isRegister(email);
        if(bool == true) {
            return ResultUtil.error(2, "该邮箱已注册！");
        }

        return ResultUtil.success();
    }

    @RequestMapping("/login/{email}/{password}")
    public ResultMsg login(@PathVariable("email") String email, @PathVariable("password") String pwd, HttpServletResponse response) {
        Token token = userService.login(email, pwd);

        if(token == null) {
            return ResultUtil.error(1, "用户名或者密码错误");
        }

        // 创建一个 cookie对象
        Cookie cookie = new Cookie("spring_cloud_token", token.getToken() );
        cookie.setPath("/");

        //将cookie对象加入response响应
        response.addCookie(cookie);

        return ResultUtil.success(token);
    }

    @RequestMapping("/info/{token}")
    public ResultMsg info(@PathVariable("token") String token) {
        String email = userService.getInfoByToken(token);
        return ResultUtil.success(email);
    }
}
